package com.pengshun.modules.Interceptor;

import com.pengshun.modules.common.BaseResult;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.multipart.MultipartException;


@ControllerAdvice
@ResponseBody
public class RuntimeExceptionHandle {


    /**
     * 所有验证框架异常捕获处理
     *
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = {BindException.class, MethodArgumentNotValidException.class})
    public Object validationExceptionHandler(Exception exception) {
        BindingResult bindResult = null;
        if (exception instanceof BindException) {
            bindResult = ((BindException) exception).getBindingResult();
        } else if (exception instanceof MethodArgumentNotValidException) {
            bindResult = ((MethodArgumentNotValidException) exception).getBindingResult();
        }
        String msg;
        if (bindResult != null && bindResult.hasErrors()) {
            msg = bindResult.getAllErrors().get(0).getDefaultMessage();
            if (msg.contains("NumberFormatException")) {
                msg = "参数类型错误！";
            }
        } else {
            msg = "系统繁忙，请稍后重试...";
        }
        return new BaseResult(1, msg);
    }

    /**
     * 连接超时异常获取
     *
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(RedisConnectionFailureException.class)
    public BaseResult RedisConnectionFailureException(Exception e) {
        System.err.println(e.getMessage());
        return new BaseResult(1, "连接超时!");
    }

    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public BaseResult handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return new BaseResult(1, "请求方式错误");
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public BaseResult handleHttpMediaTypeNotSupportedException(Exception e) {
        return new BaseResult(1, "类型错误");
    }

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public BaseResult handleException(Exception e) {
        System.err.println(e.getMessage());
        BaseResult baseResult = new BaseResult();
        if (e instanceof MethodArgumentNotValidException) {
            BindingResult result = ((MethodArgumentNotValidException) e).getBindingResult();
            StringBuilder errorMsg = new StringBuilder();
            for (ObjectError error : result.getAllErrors()) {
                errorMsg.append(error.getDefaultMessage()).append(",");
            }
            errorMsg.delete(errorMsg.length() - 1, errorMsg.length());
            baseResult.setCode(1);
            baseResult.setErrors(errorMsg.toString());
            return baseResult;
        } else if (e instanceof BindException) {
            BindingResult result = ((BindException) e).getBindingResult();
            StringBuilder errorMsg = new StringBuilder();
            for (ObjectError error : result.getAllErrors()) {
                errorMsg.append(error.getDefaultMessage()).append(",");
            }
            errorMsg.delete(errorMsg.length() - 1, errorMsg.length());
            baseResult.setCode(1);
            baseResult.setErrors(errorMsg.toString());
            return baseResult;
        } else {
            return new BaseResult(1, e.getMessage());
        }
    }


    /**
     * 500 - Internal Server Error
     * 文件上传限制
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MultipartException.class)
    public BaseResult handleException(MultipartException e) {
        return new BaseResult(1, "上传错误");
    }

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(ResourceAccessException.class)
    public BaseResult ResourceAccessException(ResourceAccessException e) {
        System.err.println(e.getMessage());
        return new BaseResult(1, "系统超时");
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(NumberFormatException.class)
    public BaseResult NumberFormatException(NumberFormatException e) {
        System.err.println(e.getMessage());
        return new BaseResult(1, "数据类型错误");
    }

    /**
     * 500 - Internal Server Error
     */
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(UsernameNotFoundException.class)
    public BaseResult usernameNotFoundException(UsernameNotFoundException e) {
        return new BaseResult(1, "用户不存在");
    }
}
